package cn.smart.tokenx.interceptors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import cn.smart.core.exception.BizException;

import cn.smart.core.model.UserSession;
import cn.smart.core.util.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TokenInterceptor implements HandlerInterceptor {
    private String jwtKey;
    public TokenInterceptor(String jwtKey){
        this.jwtKey =jwtKey;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token"); // 从请求头中获取token
        if(ObjectUtil.isEmpty(token)){
            BizException.throwBizException(403,"token不能为空");
        }
        //开始验证token
        boolean b = false;
        try {
            JWTValidator.of(token)
                    .validateAlgorithm(JWTSignerUtil.hs256(jwtKey.getBytes())) // 验证第3部分的签名是否正确
                    .validateDate(DateUtil.date()); //验证是否过期
            b=true;
        }
        catch (ValidateException ex){
            ex.printStackTrace();
            BizException.throwBizException(406,"token时间过期");
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        if(b==false){
            //验证不通过
            BizException.throwBizException(403,"token不正确或失效");
        }
        //验证通过
        final JWT jwt = JWTUtil.parseToken(token);
        UserSession userSession = JSONUtil.toBean(jwt.getPayload().toString(), UserSession.class);
        UserContext.set(userSession); //把userSession 贴到当前线程的脑门上

        return  true;
    }
}
